package com.zxy.service;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjUtil;
import com.zxy.dao.InventoryDao;
import com.zxy.dao.InventoryLogDao;
import com.zxy.model.Inventory;
import com.zxy.model.InventoryLog;
import com.zxy.model.InventoryQuery;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class InventoryService {
//    库存表

    @Autowired
    private InventoryDao inventoryDao;
    @Autowired
    private InventoryLogDao inventoryLogDao;
//    操作 InventoryLog 类型，指定加或者减
    public void  option(InventoryLog inventoryLog){
        // 1. 之前的数据,操作之后
        int beforeQty = 0;
        int afterQty = 0;
        //2. 查商品有没有库存
        Inventory inventory = inventoryDao.select(InventoryQuery.builder().id(inventoryLog.getProductId()).build());
        if(ObjUtil.isNotEmpty(inventory)){
            beforeQty = inventory.getQty();
            afterQty = beforeQty + inventoryLog.getOptionQty() * inventoryLog.getOptionType();
            //3. 跟新库存量
            inventoryDao.update(inventory.getId(),inventoryLog.getOptionQty());
        } else {
            //4. 插入库存表
            Inventory inventory2 = new Inventory();
            inventory2.setId(inventoryLog.getProductId());
            inventory2.setQty(inventoryLog.getOptionQty());
            inventory2.setProductName(inventoryLog.getProductName());

            inventory2.setProductionDate(inventoryLog.getProductionDate());
            inventory2.setExpirationDay(inventoryLog.getExpirationDay());

            DateTime dateTime = DateUtil.offsetDay(DateUtil.date(inventoryLog.getProductionDate()), inventoryLog.getExpirationDay());
            inventory2.setExpirationDate(DateUtil.toLocalDateTime(dateTime).toLocalDate());

            inventory2.setShelfId(inventoryLog.getShelfId());
            inventoryDao.insert(inventory2);
            afterQty =   inventoryLog.getOptionQty() * inventoryLog.getOptionType();
        }
        inventoryLog.setAfterQty(afterQty);
        inventoryLog.setBeforeQty(beforeQty);
        inventoryLogDao.insert(inventoryLog);
    }

    public List<Inventory> select(InventoryQuery query) {
        return inventoryDao.selectList(query);
    }
}